const { operation } = require('../../exam')
const jwt = require('jsonwebtoken')
const { nanoid } = require('nanoid')
const config = require('../../config')
const {getTime} = require('../../utils/getTime')

let attr = [
    'id',
    'nickname',
    'username',
    'sex',
    'phone',
    'mail',
    'updator',
    'avatar',
    'role_id'
].toString()

// 登录
exports.login = async ({ username, password }) => {
    try {
        let sql = `select password from users where username='${username}'`
        let userData = await operation(sql)
        if (!userData) return { msg: '请输入正确的用户名', code: '400' }
        let pass = jwt.verify(userData.password, config.jwt.secret)
        if (pass !== password) return { msg: '登陆失败 密码错误1', code: '400' }
        let sql2 = `select ${attr} from users where username='${username}' and password='${userData.password}'`
        let res = await operation(sql2)
        if (!res) return { msg: '登陆失败1', code: '400' }
        let token = jwt.sign(res.username, config.jwt.secret) + "@" + res.password + nanoid()
        if (res) return { msg: '登陆成功', code: '200', data: res, token }
        return { msg: '登陆失败2', code: '400' }
    } catch (err) { return { msg: '登陆失败3', code: '400', err } }
}

// 注册
exports.register = async ({ username, password, nickname }) => {
    try {
        let res = await operation(`select username from users where username='${username}'`)
        if (res) return { msg: '注册失败 用户已存在', code: '400' }
        let pass = jwt.sign(password, config.jwt.secret)
        let createdate = getTime()
        await operation(`insert into users(username,password,nickname,createdate) values('${username}','${pass}','${nickname}','${createdate}')`)
        return { msg: '注册成功', code: '200' }
    } catch (err) { return { msg: '注册失败', code: '400', err } }
}